import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {PageSubject} from '../../util/page-subject';
import {ResponseUtil} from '../../util/response-util';
import {OneDialogService} from '../../widgets/one-dialog/one-dialog.service';
import {UnifiedcodeService} from './unifiedcode.service';
import {TableUtil} from '../../util/table-util';
import {OneOperationComponent} from '../../widgets/one-operation/one-operation.component';
import {Unifiedcode} from './unifiedcode';
import {API, MsgConstants} from '../../constants/constants';
import {MsgResult} from '../../models/msg-result';
import {TreeUtil} from '../../util/tree-util';

declare var $;
declare var moment;

@Component({
  selector: 'app-unifiedcode',
  templateUrl: './unifiedcode.component.html',
  styleUrls: ['./unifiedcode.component.css']
})
export class UnifiedcodeComponent implements OnInit, AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;
  proxy = {
    'codeChangAdd': () => this.codeChangAdd(),
    'codeChangSave': () => this.codeChangSave(),
    'codeChangDelete': () => this.codeChangDelete()
  };
  // 站点
  myCode = '';
  name = '';
  catalogCode = '';
  // 组分数据

  table: any;
  siteArr: Array<any> = [];
  uniCode: Unifiedcode;

  // 是否弹出
  isDialog = false;

  // 是否新行
  isNewRow = false;

  // 是否按键按下
  isEnter = false;

  // 删除数据id
  ids: Array<string> = [];
  notIdsData: Array<string> = [];

  // ztree对象
  treeObj: any;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private pageSubject: PageSubject,
    private responseUtil: ResponseUtil,
    private codeService: UnifiedcodeService,
    private dialogService: OneDialogService,
    private tableUtil: TableUtil,
    private treeUtil: TreeUtil
  ) {
    this.uniCode  = new Unifiedcode();
  }

  ngOnInit() {
    this.pushPage();
    this.initData();
    this.editTdBlur();
    this.editTdEnter();
    this.initResCaTree();
  }
  ngAfterViewInit() {
    // 操作函数代理
    this.operation.proxy = this.proxy;
  }
  /**
   * 面包屑导航
   */
  pushPage() {
    // const path = new Path('数据矫正', '');
    this.pageSubject.pushPage('统一编码转换', '查询');
  }

  /**
   * 初始化数据
   */
  initData() {
  }
  loadVocsOri() {
    this.table = this.tableUtil.load('one_table_unified-code',  {
      columns: [
        {checkbox: true},
        {field: 'myCode', title: '本系统编码', valign: 'middle', align: 'left', halign: 'left',
          formatter: (value, row, index) => {
            return this.formatterEdit(value, row, index, 'myCode', '本系统编码')
          }},
        {field: 'inCode', title: '第三方导入编码', valign: 'middle', align: 'left', halign: 'left',
          formatter: (value, row, index) => {
            return this.formatterEdit(value, row, index, 'inCode', '第三方导入编码')
          }},
        {field: 'outCode', title: '导出给第三方编码', valign: 'middle', align: 'left', halign: 'left',
          formatter: (value, row, index) => {
            return this.formatterEdit(value, row, index, 'outCode', '导出给第三方编码')
          }},
        {field: 'gbCode', title: '国标编码', valign: 'middle', align: 'left', halign: 'left',
          formatter: (value, row, index) => {
            return this.formatterEdit(value, row, index, 'gbCode', '国标编码')
          }},
        {field: 'dictCode', title: '字典对应编码', valign: 'middle', align: 'left', halign: 'left',
          formatter: (value, row, index) => {
            return this.formatterEdit(value, row, index, 'dictCode', '字典对应编码')
          }},
        {field: 'name', title: '编码中文名称', valign: 'middle', align: 'left', halign: 'left',
          formatter: (value, row, index) => {
            return this.formatterEdit(value, row, index, 'name', '编码中文名称')
          }},
        {field: 'enName', title: '编码英文名称', valign: 'middle', align: 'left', halign: 'left',
          formatter: (value, row, index) => {
            return this.formatterEdit(value, row, index, 'enName', '编码英文名称')
          }},
        {field: 'catalogCode', title: '资源目录编码', valign: 'middle', align: 'left', halign: 'left'}, /*, visible: false*/
        {field: 'isUse', title: '是否使用', valign: 'middle', align: 'center', halign: 'center', formatter: this.formatterIsUse},
        // {field: 'creatorUser', title: '创建人', align: 'left', visible: false},
        // {field: 'creatorDate', title: '创建日期', align: 'left', visible: false},
        // {field: 'codeChangSaveUser', title: '修改人', align: 'left', visible: false},
        // {field: 'codeChangSaveDate', title: '修改日期', align: 'left', visible: false}
      ],
      idField: 'id',
      // sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      singleSelect: false, // 多选
      clickToSelect: false, // 点击选中
      toolbar: '#one_operation_unified-code',
      url: API.unifiedcode,
      method: 'get',
      // 传递附加参数
      queryParams: (params) => {
        params.myCode = this.myCode;
        params.name = this.name;
        params.catalogCode = this.catalogCode;
        return params;
      },
      // 返回数据处理器
      responseHandler: (result) => {
        if (result.data) {
          return result.data
        } else {
          return []
        }
      },
      height: 700, // table高度
      sortable: true,
      order: 'asc',
      classes: 'table table-hover',
      showColumns: true, // 显示自定义显示列按钮
      showRefresh: true, // 显示刷新按钮
      minimumCountColumns: 3, // 最少保留显示的列数量
      showToggle: true, // 显示视图切换按钮
      showPaginationSwitch: true, // 显示是否分页切换按钮
      striped: true, // 隔行变色
      mobileResponsive: true, // 响应式
      onClickRow: (row, elem, field) => {
        const childrenIndex = $(elem).index();
        if (field === 'isUse') {
          if ($(elem).find('input.isUse').is(':checked')) {
            row.isUse = '1';
          } else {
            row.isUse = '0';
          }
          this.table.bootstrapTable('updateCell', {index: childrenIndex, field: 'isUse', value: row.isUse});
        }
        if (row.isEdit) {
          return false;
        } else {
          row.isEdit = true;
          this.table.bootstrapTable('updateRow', {index: childrenIndex, row})
        }
      },
      onPostBody: () => {
        if (this.isNewRow) {
          this.elemGetFoucs(this.table.bootstrapTable('getData').length - 1, 1);
          this.isNewRow = false;
        }
      }
    });
  }
  formatterEdit = (value, row, index, field, title) => {
    if (row.hasOwnProperty('isEdit') && row.isEdit) {
      return '<input type="text" ' +
        'value="' + (value || '') + '" class="one-table-td-edit" ' +
        'data-index="' +  index + '" data-title="' + title +
        '" data-field="' + field + '"/>'
    } else {
      return value;
    }
  };
  formatterIsUse = (value) => {
    if (value === '1') {
      return '<input type="checkbox" checked class="isUse"/>'
    } else {
      return '<input type="checkbox" class="isUse"/>'
    }
  };
  search () {
    this.table.bootstrapTable('refresh');
  }
  codeChangAdd() {
    this.uniCode.catalogCode = this.catalogCode;
    this.isNewRow = true;
    const tableData = this.table.bootstrapTable('getData');
    if (tableData.length > 0) {
      this.uniCode.index = tableData[tableData.length - 1].index + 1;
    } else {
      this.uniCode.index = tableData.length;
    }
    this.table.bootstrapTable('append', JSON.parse(JSON.stringify(this.uniCode)));
  }
  codeChangDelete() {
    const tableData = this.table.bootstrapTable('getSelections');
    if (tableData.length <= 0) {
      this.dialogService.info('请选择一条数据');
    } else {
      const idData = tableData.filter((val) => {
        return val.id;
      });
      this.ids = this.tableUtil.getIds(idData);
      this.dialogService.modalInfoWithCancelBtn('确定删除', this.handleDeleteRequest);
      const notIdData = tableData.filter((val) => {
        return !val.id;
      });
      if (notIdData.length > 0) {
        this.table.bootstrapTable('remove', {field: 'index', values: this.tableUtil.getCloumns(tableData, 'index')});
      }
    }
  }
  codeChangSave() {
    const tableData = this.table.bootstrapTable('getData');
    const repeat = this.judgeAllDataRepeat(tableData);
    if (repeat[0]) {
      const info: Array<any> = [];
      repeat[1].forEach((val) => {
        info.push('第' + val.index + '行' + val.title);
      });
      this.dialogService.info(info.join(' ， ') + '数据重复');
    } else {
      this.codeService.saveCode(tableData).subscribe(
        result => this.responseUtil.success(result, () => {
          if (result.code === MsgConstants.MSG_CODE_OK) {
            tableData.forEach((val) => {
              val.isEdit = false;
            });
            this.table.bootstrapTable('load', tableData);
            this.dialogService.success(result.message);
          } else {
            this.dialogService.info(result.message);
          }
        }),
        error => this.responseUtil.error(error)
      )
    }
  }

  handleDeleteRequest = () => {
    this.codeService.deleteCode(this.ids.join(',')).subscribe(
      result => this.responseUtil.success(result, () => {
        if (result.code === MsgConstants.MSG_CODE_OK) {
          this.dialogService.success(result.message);
          this.table.bootstrapTable('remove', {field: 'id', values: this.ids})
        } else {
          this.dialogService.info(result.message);
        }
      }),
      error => this.responseUtil.error(error)
    )
  };

  /**
   * 给可编辑的input框绑定blur事件
   */
  editTdBlur = () => {
    $('#one_table_unified-code').on('blur', '.one-table-td-edit', (e) => {
      const elem = $(e.target);
      const index = elem.data('index');
      const field = elem.data('field');
      const value = elem.val();
      const title = elem.data('title');
      const childrenIndex = elem.parent().index();
      this.table.bootstrapTable('updateCell', {index: index, field: field, value: value});
      const repeat = this.judgeDataRepeat(this.table.bootstrapTable('getData'), field);
      if (repeat[0] && value) {
        setTimeout(() => {
          const focusElem = this.getElemFocus(index, childrenIndex);
          if (!focusElem.is(':focus')) {
            if (!this.isDialog) {
              this.dialogService.info('第' + repeat[1] + '行' + title + '重复，请重新输入',
                () => this.elemGetFoucs(index, childrenIndex),
                () => this.elemGetFoucs(index, childrenIndex),
                () => this.elemGetFoucs(index, childrenIndex)
              );
            } else {
              this.isDialog = false;
            }
            focusElem.focus();
          }
        }, 500)
      } else if (this.isEnter) {
        this.isEnter = false;
        const inputLength = $(e.target).parent().next().children('.one-table-td-edit').length;
        const trLength = this.table.bootstrapTable('getData').length;
        if (inputLength > 0) {
          setTimeout(() => {
            this.elemGetFoucs(index, childrenIndex + 1);
          }, 500)
        } else if (trLength === (index + 1)) {
          this.codeChangAdd();
        } else {
          this.elemGetFoucs(index + 1, 1);
        }
      }
    })
  };
  /**
   * input框获取焦点
   */
  elemGetFoucs = (index, childrenIndex) => {
    const focusElem = this.getElemFocus(index, childrenIndex);
    focusElem.focus();
  };
  /**
   * 获取需要获取焦点的input框
   */
  getElemFocus = (index, childrenIndex) => {
    return $('#one_table_unified-code')
      .find('tbody tr:nth-child(' + (index + 1) + ')')
      .find(' td:nth-child(' + (childrenIndex + 1) + ') input');
  };

  /**
   * 给可编辑的input框绑定键盘按下事件，enter键或tab键跳转至下一输入框
   */
  editTdEnter = () => {
    const tableElem = $('#one_table_unified-code');
    tableElem.on('keydown', (e) => {
      if (e.keyCode === 13 || e.keyCode === 9) {
        const elem = tableElem.find('.one-table-td-edit:focus');
        const keyDownTrIndex = elem.data('index');
        const keyDownTdIndex = elem.parent().index() + 1;
        this.isEnter = true;
        const inputLength = $(e.target).parent().next().children('input').length;
        if (inputLength > 0 ) {
          this.elemGetFoucs(keyDownTrIndex, keyDownTdIndex);
        } else {
          this.elemGetFoucs(keyDownTrIndex, keyDownTdIndex + 1);
        }
      }
    })
  };
  /**
   * 判断某列数据是否重复
   */
  judgeDataRepeat = (arr, field) => {
    const obj = {};
    let isRepeat = false;
    let repeatIndex = 0;
    arr.every((val, i) => {
      if (val[field]) {
        if (obj[val[field]]) {
          repeatIndex = i;
          isRepeat = true;
          return false
        } else {
          obj[val[field]] = true;
          return true;
        }
      } else {
        return true;
      }
    });
    return [isRepeat, repeatIndex];
  };
  /**
   * 判断所有数据是否重复
   */
  judgeAllDataRepeat = (arr) => {
    const repeatArr = [];
    const repeatIndexArr: Array<any> = [];
    const repeatData: Array<any> = [];
    let isRepeat = false;
    const option = this.table.bootstrapTable('getOptions');
    option.columns[0].forEach((val) => {
      if (val.hasOwnProperty('field') && ( val.field !== 'catalogCode' && val.field !== 'isUse')) {
        const fieldRepeat = this.judgeDataRepeat(arr, val.field);
        repeatArr.push(fieldRepeat[0]);
        if (fieldRepeat[0]) {
          repeatIndexArr.push(
            {
              index: this.judgeDataRepeat(arr, val.field)[1],
              title: val.title
            }
          );
        }
      }
    });
    if (repeatArr.indexOf(true) !== -1) {
      isRepeat = true;
    }
    repeatData.push(isRepeat, repeatIndexArr);
    return repeatData;
  };
  /**
   * 初始化菜单树
   */
  initResCaTree() {
    this.codeService.getRescatalog('1').subscribe(
      result => this.responseUtil.success(result, this.processMenuTreeResult),
      message => this.responseUtil.error(message)
    );
  }
  private processMenuTreeResult = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.initResCaTreeObj(result.data);
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  initResCaTreeObj(data) {
    // 初始化菜单树
    const setting = {
      callback: {
        onClick: this.clickTree
      },
      data: {
        key: {
          name: 'resName'
        }
      }
    };
    // 把树放进页面
    this.treeObj = $.fn.zTree.init($('#resCatalogUniZTree'), setting, this.treeUtil.wrapToStandard(data));
    /**
     * 默认选中第一个
     */
    const nodes = this.treeObj.getNodes();
    if (nodes.length > 0) {
      this.treeObj.selectNode(nodes[0]);
      this.catalogCode = nodes[0].resCode;
    }
    this.loadVocsOri();
  }
  clickTree = (event, treeId, treeNode) => {
    if (treeNode.resCode === this.catalogCode) {
      // const selectedArray: Array<object> = this.treeObj.getSelectedNodes();
      // if (selectedArray.length > 0) {
      //   this.treeObj.cancelSelectedNode(selectedArray[0]);
      // }
      // this.catalogCode = '';
    } else {
      this.catalogCode = treeNode.resCode;
    }
    this.search();
  };
}
